/*
* $Id: spif.c,v 1.4 2007/11/13 09:02:02 sunny Exp $
*/
/*******************************************************************************

       UBEC (Uniband Electronic Corp.)

       Project: U-NET01, Ubiquitous network platform

       File: spif.c

       Version: 0.2.3

       Usage: SPI Interface Function

       Platform: U-NET01 DK with Keil 8051 C compiler

       Reference:

               Silicon Laboratories: C8051F124, C8051F340

               UBEC: UZ2400, UZ2410

       Note :

               Copyright (C) 2007 Uniband Electronic Corporation, All rights reserved

********************************************************************************/

#include "unet.h"

void InitSPI(void)	// Init MCU's SPI Register
{
#ifdef GPIO_SPI
	SPI_SS   =  1;
	SPI_SCK  =  0;
	SPI_MOSI =  0;

#elif defined(M430F1611)
	enable_uz2400_cs_output();
	enable_uz2400_reset_output();

	P3SEL |= 0x0E;				// Setup P3.1,2,3 for SPI mode
	U0CTL |= CHAR + SYNC + MM;		// 8-bit, SPI, Master
	U0TCTL |= CKPH + SSEL1 + STC;		// Polarity, SMCLK, 3-wire
	U0BR0 = 0x02;				// SPICLK = SMCLK/2
	U0BR1 = 0x00;
	U0MCTL = 0x00;
	ME1 = USPIE0;				// Module enable
	U0CTL &= ~SWRST;			// SPI enable

#else
	#error "Unknown CPU type."
#endif
}

#pragma message (__LOC__ "spi_rw() is called by interrupt service routine and main program.")
UINT8 spi_rw(UINT8 c)
{
#ifdef	GPIO_SPI
	UINT8 i;

	for(i=8; i--; )	{
		// Write the output bit
		SPI_MOSI = c & 0x80;

		// shift one bit
		c <<= 1;

		// clock HIGH
		SPI_SCK = 1;

		// Read the input bit
		c |= SPI_MISO;

		// clock LOW
		SPI_SCK = 0;
	}

#elif defined(M430F1611)

	TXBUF = c;		// Send the opcode and address.
	while(!RIF);		// Wait until opcode/address is transmitted.
	c = RXBUF;

#else
	#error "Unknown CPU type."
#endif

	return(c);
}
